<template>
  <ApproveWrapper>
    <template v-slot:header v-if="isShowHeader">
      <CommonFormEditorHeader @save="save" :formDataVoRef="formDataVoRef"/>
    </template>

    <template v-slot:body>
      <DefaultFormRender :pageAction="pageAction" :formDefinition="formDefinition" :viewAction="viewAction"
                         ref="refDefaultFormRender" :view="view" :components="components"/>

      <FSection title="相关附件" v-show="isNotEmpty(formFlowDesc)
      && isNotEmpty(formFlowDesc.attachmentIds)"
                :style="{width: (view.width + 40) + 'px'}"
                class="start-process-content-section">
        <FUploader ref="refFUploader" :enable="isShowHeader"/>
      </FSection>

      <FSection title="附言" :style="{width: (view.width + 40) + 'px'}"
                class="start-process-content-section">
        <el-text v-if="isShowHeader">
          <froala id="edit" :tag="'textarea'" placeholder="请输入附言" :config="froalaConfig"
                  v-model:value="formFlowDesc.additionalComments"></froala>
        </el-text>
        <el-text v-else-if="isNotEmpty(formFlowDesc.additionalComments)">
          <div v-html="formFlowDesc.additionalComments">
          </div>
        </el-text>
      </FSection>

    </template>
  </ApproveWrapper>
</template>
<script setup>
import ApproveWrapper from '@/components/platwork/FormApproveComponent/ApproveWrapper.vue';
import {computed, getCurrentInstance, onMounted, shallowRef, toRaw, unref} from 'vue';
import CommonFormEditorHeader from '@/components/platwork/CommonFormEditor/CommonFormEditorHeader.vue';
import DefaultFormRender
  from '@/components/platwork/FormDetailComponent/DefaultFormDetailComponent/DefaultFormRender.vue';
import {isEmpty, isNotEmpty} from '@/utils/CommonUtils';
import FSection from '@/components/FSection/index.vue';
import FUploader from '@/components/FUploader/index.vue';
import {getAction, postAction} from '@/request/BaseRequest';
import {useRoute} from 'vue-router';
import {DefaultViewAction, DefaultViewDefinition} from '@/components/form/DefaultFormDefinition';
import {_froalaConfig} from '@/components/MyFroala';

defineOptions({
  name: 'CommonFormEditor'
});

const internalInstance = getCurrentInstance();
const global = internalInstance.appContext.config.globalProperties;

const pageAction = shallowRef('detail');
const formDefinition = shallowRef({
  form: {},
  formFields: [],
  subForms: [{
    fields: [],
    subForm: {}
  }]
});
const viewAction = shallowRef(DefaultViewAction);
const view = shallowRef(DefaultViewDefinition);
const components = shallowRef([]);
const formFlowDesc = shallowRef({});
const refDefaultFormRender = shallowRef();
const refFUploader = shallowRef();
const formDataVoRef = shallowRef();
const route = useRoute();
const loading = shallowRef(false);
const froalaConfig = shallowRef({
  ..._froalaConfig,
  zIndex: 1,
});

onMounted(() => {
  if (route.query.action === 'edit') {
    loadEditDatas();
  }
  if (route.query.action === 'detail') {
    loadDetailDatas();
  }
});

function loadDetailDatas() {
  loadViewForm(route.query.viewId).then(_formDefinition => {
    resolveFormDefinition(_formDefinition);

    loadFormData().then(formDataVo => {
      setFormData(formDataVo);
    });
  });
}

function loadEditDatas() {
  loadViewActionForm(route.query.viewActionId).then(_formDefinition => {
    resolveFormDefinition(_formDefinition);

    loadFormData().then(formDataVo => {
      setFormData(formDataVo);
    });
  });
}

function loadViewForm(viewId) {
  return new Promise((success, err) => {
    getAction('/plat/loadViewFormDefinitionPublished', {viewId}).then(data => {
      if (data.success) {
        let result = data.result;
        setViewActionIdFormDefinitionPublished(result);

        success(formDefinition);
      }
    });
  });
}


function setFormData(formDataVo) {
  formDataVoRef.value = formDataVo;
  refDefaultFormRender.value.setFormData(formDataVo.formData);
  formFlowDesc.value = formDataVo.formFlowDesc;
  refFUploader.value.setData(formDataVo.formFlowDesc.attachmentIds);
}

function parseFormDefinition(_formDefinition) {
  let data = {};
  data.form = _formDefinition;
  data.formFields = _formDefinition.fields;
  data.subForms = _formDefinition.subForms;
  let tempSubForms = [];
  if (isNotEmpty(_formDefinition.subForms)) {
    _formDefinition.subForms.forEach(subForm => {
      tempSubForms.push({
        fields: subForm.fields,
        subForm
      });
    });
  }
  data.subForms = tempSubForms;

  formDefinition.value = data;
  refDefaultFormRender.value.setFormDefinition(data);
}

function loadFormData() {
  return new Promise((success, err) => {
    let id = route.query.businessId;
    let formId = formDefinition.value.form.id;

    getAction('/plat/loadFormDataById', {id, formId}).then(data => {
      if (data.success) {
        let result = data.result;
        success(result);
      }
    });
  });
}

function save() {
  loading.value = true;
  createSubmitData().then(data => {
    postAction('/plat/update', data).then(data => {
      if (data.success) {
        global.$windowManager.close();
      }
      loading.value = false;
    });
  });
}

function createSubmitData() {
  return new Promise((success, err) => {
    refDefaultFormRender.value.getFormDataWithCheck().then(formData => {
      formData = unref(formData);
      formData = toRaw(formData);
      formData.processDefinitionId = formDefinition.value.form;
      formFlowDesc.value.formName = formDefinition.value.form.formName;
      formFlowDesc.value.attachmentIds = refFUploader.value.getAttachmentIds();
      let data = {
        formData,
        formFlowDesc: unref(formFlowDesc)
      };
      success(data);
    });
  });
}

function resolveFormDefinition(formDefinition) {
  let definition = unref(formDefinition).form;
  view.value = definition.views[0];
  let v = unref(view);

  let temp = v.viewDefinition;
  components.value = temp.children;
}

function loadViewActionForm(viewActionId) {
  return new Promise((success, err) => {
    getAction('/plat/loadviewActionIdFormDefinitionPublished', {viewActionId}).then(data => {
      let result = data.result;
      setViewActionIdFormDefinitionPublished(result);

      success(formDefinition);
    });
  });
}

function setViewActionIdFormDefinitionPublished(result) {
  setViewDefinition(result.views[0]);
  setViewAction(result.viewAction);
  setFormDefinition1(result);
}

function setViewDefinition(data) {
  data.viewDefinition = JSON.parse(data.viewDefinition);
  view.value = data;
  components.value = view.value.viewDefinition.children;
}

function setViewAction(_viewAction) {
  viewAction.value = _viewAction;
}

function setFormDefinition1(_formDefinition) {
  if (isEmpty(_formDefinition)) return;
  formDefinition.value.form = _formDefinition;
  formDefinition.value.formFields = _formDefinition.fields;
  formDefinition.value.formRelationVos = _formDefinition.formRelationVos;

  let tempSubForms = [];
  if (isNotEmpty(_formDefinition.subForms)) {
    _formDefinition.subForms.forEach(subForm => {
      tempSubForms.push({
        fields: subForm.fields,
        subForm
      });
    });
  }
  formDefinition.value.subForms = tempSubForms;
  refDefaultFormRender.value.setFormDefinition(formDefinition);
}

const isShowHeader = computed(() => {
  if (route.query.action === 'detail') {
    return false;
  }
  return true;
});

</script>
